package http

import (
	"crypto/tls"
	"io"
	"net"
	"net/http"
	"time"
)

var Cli HttpClient

type HttpClient interface {
	Request(headers map[string]string, method, url string, body io.Reader) (resp *http.Response, err error)
}

type Client struct {
	*http.Client
}

func InitClient() {
	timeout := 15 * time.Second
	transport := &http.Transport{
		DialContext: (&net.Dialer{
			Timeout:   30 * time.Second,
			KeepAlive: 30 * time.Second,
		}).DialContext,
		MaxIdleConns:          100,
		IdleConnTimeout:       90 * time.Second,
		TLSHandshakeTimeout:   10 * time.Second,
		ExpectContinueTimeout: 1 * time.Second,
		TLSClientConfig:       &tls.Config{InsecureSkipVerify: true}, // 跳过证书验证(不推荐生产环境使用)
	}

	Cli = &Client{
		&http.Client{
			Timeout:   timeout,
			Transport: transport,
		},
	}
}

// 注意关闭resp.Body
func (c *Client) Request(
	headers map[string]string,
	method, url string,
	body io.Reader,
) (resp *http.Response, err error) {

	req, err := http.NewRequest(method, url, body)
	if err != nil {
		return nil, err
	}
	for k, v := range headers {
		req.Header.Add(k, v)
	}

	resp, err = c.Client.Do(req)
	if err != nil {
		return resp, err
	}
	return resp, nil
}
